package org.example.mallchat.common.event.listener;

import lombok.extern.slf4j.Slf4j;
import org.example.mallchat.common.event.UserRegisterEvent;
import org.example.mallchat.domain.entity.User;
import org.example.mallchat.domain.enums.IdempotentEnum;
import org.example.mallchat.domain.enums.ItemEnum;
import org.example.mallchat.service.iservice.ItemService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

import javax.annotation.Resource;

/**
 * @author: zzh
 * @date: 2024/12/24 13:32:50
 * @version: 1.0
 */
// 事件监听器Spring容器的！
@Slf4j
@Component
public class UserRegisterListener {

    @Resource
    private ItemService itemService;

    // 监听UserRegisterEvent事件
    @Async// 异步处理
    @TransactionalEventListener(classes = UserRegisterEvent.class, phase = TransactionPhase.AFTER_COMMIT,fallbackExecution = true)
    public void onUserRegister(UserRegisterEvent event) {
        log.info("Received UserRegisterEvent: {}", event);
        // 用户注册后 发放改名卡一张
        User user = event.getUser();
        itemService.acquireItemToUser(user.getId(), ItemEnum.MODIFY_NAME_CARD.getId(), IdempotentEnum.UID_IDEMPOTENT, user.getOpenId());
    }
}
